package com.scenic.scenicservice.controller;

import com.scenic.common.bean.Category;
import com.scenic.common.bean.RespBean;
import com.scenic.common.exception.ScenicSpotException;
import com.scenic.common.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //添加
    @PostMapping
    public RespBean insert(@RequestBody Category category) throws ScenicSpotException {
        categoryService.insert(category);

        return RespBean.ok("添加成功");
    }
    //根据id删除
    @DeleteMapping(("/{id}"))
    public RespBean delete(@PathVariable("id") Integer id) throws ScenicSpotException {
        categoryService.delete(id);

        return RespBean.ok("删除成功");
    }
    //根据id修改
    @PutMapping
    public RespBean update(@RequestBody Category category) throws ScenicSpotException {
        categoryService.update(category);

        return RespBean.ok("修改成功");
    }
    //条件分页搜索
    @GetMapping("/search")
    public RespBean selectByPage (Category category, Integer pageNum, Integer pageSize){

        Object data = categoryService.selectByCondition(category, pageNum, pageSize);

        return RespBean.ok("",data);
    }
    //根据id查询
    @GetMapping("/{id}")
    public RespBean selectById(@PathVariable("id") Integer id){
        return RespBean.ok("",categoryService.selectById(id));
    }
    //获取所有的父分类
    @GetMapping("/allparent")
    public RespBean selectAllParent(){
        Category category = new Category();
        category.setParentId(0);
        //查询在redis中查询所有的父分类
        //String allParentJson = stringRedisTemplate.opsForValue().get(CATEGORY_CACHE);
        //
        ////判断是否缓存命中
        //if (!StrUtil.isBlank(allParentJson)) {
        //    Object allparent = JSONUtil.toBean(allParentJson, Object.class);
        //    return RespBean.ok("",allparent);
        //}
        //为命中将查询的数据存入redis
        Object data = categoryService.selectByCondition(category, null, null);
        //stringRedisTemplate.opsForValue().set(CATEGORY_CACHE, JSONUtil.toJsonStr(data), CATEGORY_CACHE_TIME, TimeUnit.MINUTES);
        return RespBean.ok("",data);
    }

}
